<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :title="vdata.isAdd ? '新增支付接口' : vdata.isCloneMode ? '克隆接口' : '修改支付接口'"
    width="40%"
    :maskClosable="false"
    @close="onClose"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">
      <p class="jee-drawer-title">支持配置</p>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="是否支持普通商户模式" name="isMchMode">
            <a-radio-group v-model:value="vdata.saveObject['isMchMode']" :disabled="!vdata.isAdd">
              <a-radio :value="1">
                支持
              </a-radio>
              <a-radio :value="0">
                不支持
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否支持服务商子商户模式" name="isIsvMode">
            <a-radio-group v-model:value="vdata.saveObject['isIsvMode']" :disabled="!vdata.isAdd">
              <a-radio :value="1">支持</a-radio>
              <a-radio :value="0">不支持</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="是否支持进件" name="isSupportApplyment">
            <a-radio-group v-model:value="vdata.saveObject['isSupportApplyment']" :disabled="!vdata.isAdd">
              <a-radio :value="1">
                支持
              </a-radio>
              <a-radio :value="0">
                不支持
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item label="是否支持对账" name="isSupportCheckBill">
            <a-radio-group v-model:value="vdata.saveObject['isSupportCheckBill']" :disabled="!vdata.isAdd">
              <a-radio :value="1">
                支持
              </a-radio>
              <a-radio :value="0">
                不支持
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否支持提现" name="isSupportCashout">
            <a-radio-group v-model:value="vdata.saveObject['isSupportCashout']" :disabled="!vdata.isAdd">
              <a-radio :value="1">
                支持
              </a-radio>
              <a-radio :value="0">
                不支持
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        
        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">基本配置</p>
        <a-col :span="12">
          <a-form-item label="接口代码" name="ifCode">
            <a-input v-model:value="vdata.saveObject['ifCode']" placeholder="请输入" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="接口名称" name="ifName">
            <a-input v-model:value="vdata.saveObject['ifName']" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="支付参数配置页面类型" name="configPageType">
            <a-radio-group v-model:value="vdata.saveObject['configPageType']" :disabled="!vdata.isAdd">
              <a-radio :value="1">
                页面渲染接口配置描述
              </a-radio>
              <a-radio :value="2">
                自定义页面
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12"> 
          <a-form-item label="是否开启进件" name="isOpenApplyment">
            <a-radio-group v-model:value="vdata.saveObject['isOpenApplyment']" :disabled="vdata.saveObject['isSupportApplyment'] == 0">
              <a-radio :value="1">
                开启
              </a-radio>
              <a-radio :value="0">
                关闭
              </a-radio>
            </a-radio-group>
            <br>
            <span v-if="vdata.saveObject['isSupportApplyment'] == 0" class="jeepay-tip-text">（当前接口不支持进件）</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否开启对账" name="isOpenCheckBill">
            <a-radio-group v-model:value="vdata.saveObject['isOpenCheckBill']" :disabled="vdata.saveObject['isSupportCheckBill'] == 0">
              <a-radio :value="1">
                开启
              </a-radio>
              <a-radio :value="0">
                关闭
              </a-radio>
            </a-radio-group>
            <br>
            <span v-if="vdata.saveObject['isSupportCheckBill'] == 0" class="jeepay-tip-text">（当前接口不支持对账）</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否开启提现" name="isOpenCashout">
            <a-radio-group v-model:value="vdata.saveObject['isOpenCashout']" :disabled="vdata.saveObject['isSupportCashout'] == 0">
              <a-radio :value="1">
                开启
              </a-radio>
              <a-radio :value="0">
                关闭
              </a-radio>
            </a-radio-group>
            <br>
            <span v-if="vdata.saveObject['isSupportCashout'] == 0" class="jeepay-tip-text">（当前接口不支持提现）</span>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject['isIsvMode'] == 1 && vdata.saveObject['configPageType'] === 1" :span="24">
          <a-form-item label="服务商接口配置定义描述" name="isvParams">
            <a-textarea v-model:value="vdata.saveObject['isvParams']" :readonly="vdata.isCloneMode" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject['isIsvMode'] == 1 && vdata.saveObject['configPageType'] === 1" :span="24">
          <a-form-item label="特约商户接口配置定义描述" name="isvsubMchParams">
            <a-textarea v-model:value="vdata.saveObject['isvsubMchParams']" :readonly="vdata.isCloneMode" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject['isMchMode'] == 1 && vdata.saveObject['configPageType'] === 1" :span="24">
          <a-form-item label="普通商户接口配置定义描述" name="normalMchParams">
            <a-textarea v-model:value="vdata.saveObject['normalMchParams']" :readonly="vdata.isCloneMode" placeholder="请输入" type="textarea" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                停用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-input v-model:value="vdata.saveObject['remark']" placeholder="请输入" />
            <p style="color: grey;">将显示在商户APP的[通道申请]页面</p>
          </a-form-item>
        </a-col>

        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">手续费配置</p>
        <a-col :span="12">
          <a-form-item label="渠道手续费计算方式" name="feeCalModel">
            <a-radio-group v-model:value="vdata.channelFeeCalModel['feeCalModel']" :disabled="!vdata.isAdd">
              <a-radio value="BASE_FINAL_ORDER_AMOUNT">基于最新收单金额计算</a-radio>
              <a-radio value="SPLIT_PAY_REFUND_AMOUNT">收单金额和退款金额分开计算</a-radio>
            </a-radio-group>
          </a-form-item>
          <div id="components-popover-demo-placement">
            <div class="typePopover">
              <a-popover placement="top">
                <template #title><span>计算方式</span></template>
                <template #content>
                  <p>基于最新收单金额计算：<b>手续费退还金额 = 收单手续费 - （订单金额 - 退款金额） X 费率</b></p>
                  <p>收单金额和退款金额分开计算：<b>手续费退还金额 = 退款金额 X 费率</b></p>
                </template>
                <question-circle-outlined />
              </a-popover>
            </div>
          </div>
        </a-col>
        
        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">支付方式</p>
        <a-col :span="24">
          <a-form-item label="支持的支付方式" name="checkedList">
            <a-checkbox-group :value="vdata.checkedList" :options="vdata.wayCodesOptions" @change="onWayCodesChange" />
          </a-form-item>
        </a-col>

        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">转账方式</p>
        <a-form-item label="是否开启转账" name="isOpenTransfer">
          <a-radio-group v-model:value="changeTransferFlagVal" @change="changeTransferFlagFunc">
            <a-radio :value="1">开启</a-radio>
            <a-radio :value="0">关闭</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-divider class="m-b-20" />
        <p class="jee-drawer-title">页面展示</p>
        <a-col :span="12">
          <a-form-item label="卡片icon" name="icon">
            <JeepayUpload v-model:src="vdata.saveObject['icon']" bizType="ifBG" />
          </a-form-item>
        </a-col>
        <a-col :span="12" class="m-b-50">
          <a-form-item label="卡片背景色" name="bgColor">
            <a-input v-model:value="vdata.saveObject['bgColor']" type="color" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { API_URL_IFDEFINES_LIST, API_URL_PAYWAYS_LIST, req, reqLoad, upload, $queryCloneInfos } from '@/api/manage'
import { onMounted,ref,reactive, getCurrentInstance, computed } from 'vue'
import { message } from 'ant-design-vue'
const { $infoBox} = getCurrentInstance()!.appContext.config.globalProperties
    
  const infoFormModel = ref()
  const props = defineProps ({
    callbackFunc: { type: Function, default: () => () => ({}) }
  })

  
    const validateNormalMchParams = (rule, value, callback) => { // 普通商户接口配置定义描述 验证器
      if (vdata.saveObject['isMchMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入普通商户接口配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateIsvParams = (rule, value, callback) => { // 服务商接口配置定义描述 验证器
      if (vdata.saveObject['isIsvMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入服务商接口配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateIsvsubMchParams = (rule, value, callback) => { // 特约商户接口配置定义描述 验证器
      if (vdata.saveObject['isIsvMode'] === 1 && vdata.saveObject['configPageType'] === 1 && !value) {
        return Promise.reject(new Error('请输入特约商户接口配置定义描述'))
      }
      return Promise.resolve()
    }
    const validateWayCodes = (rule, value, callback) => { // 支付方式 验证器
      if (vdata.checkedList.length <= 0) {
        return Promise.reject(new Error('请选择支付方式'))
      }
      return Promise.resolve()
    }

    const vdata  : any = reactive ({
      isAdd: true, // 新增 or 修改
      visible: false, // 抽屉开关
      action: upload.ifBG, // 上传图标地址
      ifCode: '', // 支付接口定义id
      saveObject: {}, // 数据对象
      channelFeeCalModel: {}, // 渠道手续费计算方式等的配置
      btnLoading: false,
      rules: {
        ifCode: [{ required: true, message: '请输入接口代码', trigger: 'blur' }],
        ifName: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
        normalMchParams: [{ required: true, validator: validateNormalMchParams, trigger: 'blur' }],
        isvParams: [{ required: true, validator: validateIsvParams, trigger: 'blur' }],
        isvsubMchParams: [{ required: true, validator: validateIsvsubMchParams, trigger: 'blur' }],
        checkedList: [{ required: true, validator: validateWayCodes, trigger: 'blur' }]
      },
      wayCodesOptions: [] as any[], // 支付方式多选框选项列表
      checkedList: [], // 选中的数据
      isCloneMode: false, //是否克隆模式， 默认为false
    })

 
  onMounted(()=>{
      payWayList()
  })

defineExpose({show})
    // 抽屉显示
    function show (ifCode, isCloneMode) {
      vdata.isAdd = !ifCode
      vdata.isCloneMode = isCloneMode
       // 数据清空
      vdata.saveObject = {
        'isMchMode': 1,
        'isIsvMode': 1,
        'state': 1,
        'configPageType': 1,
        'isSupportApplyment': 0,
        'isOpenApplyment': 0,
        'isSupportCheckBill': 0,
        'isOpenCheckBill': 0,
        'isSupportCashout': 0,
        'isOpenCashout': 0
      }

      vdata.channelFeeCalModel = {
        'feeCalModel': 'BASE_FINAL_ORDER_AMOUNT' // （默认）基于最新收单金额计算:BASE_FINAL_ORDER_AMOUNT; 收单金额和退款金额分开计算： SPLIT_PAY_REFUND_AMOUNT
      }

      if (infoFormModel.value !== undefined) {
        infoFormModel.value.resetFields()
      }

     
      if (!vdata.isAdd) { // 修改信息 延迟展示弹层
        vdata.ifCode = ifCode
        // 拉取详情
        req.getById(API_URL_IFDEFINES_LIST, ifCode).then(res => {
          vdata.saveObject = res
          const newItems:any = [] // 多选框赋值
          res.wayCodes.forEach(item => {
            newItems.push(item.wayCode)
          })
           vdata.checkedList = newItems
           vdata.channelFeeCalModel = JSON.parse(res.channelFeeCalModel || '{}')
           if (!vdata.channelFeeCalModel['feeCalModel']) {
            // 放置初始值
            vdata.channelFeeCalModel['feeCalModel'] = 'BASE_FINAL_ORDER_AMOUNT'
           }

           // 克隆模式， 查询当前第几条。 
           if(vdata.isCloneMode){
            $queryCloneInfos(ifCode).then( cloneInfos => {
              vdata.saveObject.ifCode = cloneInfos.ifCode
              vdata.saveObject.ifName = cloneInfos.ifName
            })
           }
        })
        vdata.visible = true
      } else {
        vdata.checkedList = [] // 多选框设置空
        vdata.visible = true // 展示弹层信息
      }
    }
   function onClose () {
      vdata.visible = false
   }
    // 表单提交
  function  onSubmit () {
      infoFormModel.value.validate().then(valid =>{
          vdata.saveObject['wayCodeStrs'] = vdata.checkedList.join(',')
          vdata.saveObject['channelFeeCalModel'] = JSON.stringify(vdata.channelFeeCalModel || '{}')
          // 请求接口
          if (vdata.isAdd || vdata.isCloneMode) {
            let primaryStr = '保存后“支持配置项”及“支付参数配置页面类型”将无法进行修改，请与开发人员确认后再保存'
            $infoBox.confirmPrimary('确认新增吗？', primaryStr,() => {
              vdata.btnLoading = true // 打开按钮上的 loading
              reqLoad.add(API_URL_IFDEFINES_LIST, vdata.saveObject).then(res => {
                message.success('新增成功')
                vdata.visible = false
                props.callbackFunc() // 刷新列表
                vdata.btnLoading = false
              }).catch(valid =>{
                vdata.btnLoading = false
              })
            }, undefined, {okText:'确认保存'})
          } else {
            reqLoad.updateById(API_URL_IFDEFINES_LIST, vdata.ifCode, vdata.saveObject).then(res => {
              message.success('修改成功')
              vdata.visible = false
              props.callbackFunc() // 刷新列表
              vdata.btnLoading = false
            }).catch(valid =>{
              vdata.btnLoading = false
            })
          }
      })
    }
    // 支付方式列表
  function  payWayList () {
      req.list(API_URL_PAYWAYS_LIST, { 'pageSize': '-1' }).then(res => {
        res.records.filter(r => r.wayCode != 'TRANSFER').forEach(item => {
          vdata.wayCodesOptions.push({
            label: item.wayName,
            value: item.wayCode
          })
        })
      })
    }
 function  onWayCodesChange (checkedValues) {

      // 是否支持转账
      let isTransfer = false
      if(changeTransferFlagVal.value == 1){
        isTransfer = true
      }

      vdata.checkedList = checkedValues

      if(isTransfer){
        vdata.checkedList.push('TRANSFER')
      }
    }

// 更改 转账 状态
function changeTransferFlagFunc(v){

  // 删除 转账产品
  if(vdata.checkedList.indexOf('TRANSFER') >= 0){
    vdata.checkedList.splice(vdata.checkedList.indexOf('TRANSFER'), 1)
  }

  // 开启
  if(v.target.value){
    vdata.checkedList.push('TRANSFER')
  }

  console.log(vdata.checkedList)

}


// 计算属性 
let changeTransferFlagVal = computed(() => {
  if(vdata.checkedList.indexOf('TRANSFER') >= 0){
      return 1
    }

    return 0
}) as any


</script>

<style lang="less">
  .typePopover {
    position: absolute;
    top: 0;
    left:150px;
  }
</style>
